<template>
	<view class="product-detail-page">

		<!-- 商品图片 -->
		<image :src="goods.image" class="goods-img" mode="widthFix" />

		<!-- 商品基本信息 -->
		<view class="goods-info">
			<text class="goods-name">{{ goods.name }}</text>
			<!-- 价格显示，直接使用从分类页传递的价格格式 -->
			<text class="price">￥{{ goods.price || '价格暂无' }}束</text>
			<!-- 商品描述显示 -->
			<text class="goods-intro" v-if="goods.intro || goods.desc">
			    {{ goods.intro ? goods.intro : '商品描述：' + goods.desc }}
			  </text>
			<view class="product-tags">
				<view class="tag" v-for="(tag, index) in product.tags" :key="index">{{ tag }}</view>
			</view>
		</view>

		<!-- 商品规格选择 -->
		<view class="product-spec">
			<view class="spec-title">配送时间</view>

			<view class="spec-group" v-for="(specGroup, groupIndex) in product.specGroups" :key="groupIndex">
				<view class="spec-group-name">{{ specGroup.name }}</view>
				<view class="spec-options">
					<view class="spec-option"
						:class="{ 'spec-option-selected': specGroup.selectedValue === option.value }"
						@click="selectSpec(groupIndex, option.value)" v-for="option in specGroup.options"
						:key="option.value">
						{{ option.label }}
					</view>
				</view>
			</view>
		</view>

		<!-- 数量选择 -->
		<view class="product-quantity">
			<view class="quantity-title">购买数量</view>
			<view class="quantity-control">
				<view class="quantity-btn minus" @click="decreaseQuantity" :class="{ disabled: quantity <= 1 }">-</view>
				<view class="quantity-input">{{ quantity }}</view>
				<view class="quantity-btn plus" @click="increaseQuantity"
					:class="{ disabled: quantity >= product.stock }">+</view>
			</view>
			<view class="stock-info">库存 {{ product.stock }} 件</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="cart-btn" @click="addToCart">加入购物车</view>
			<view class="buy-btn" @click="goToCheckout">立即购买</view>
		</view>

		<!-- 加入购物车成功提示 -->
		<uni-popup ref="cartPopup" type="center" :mask-click="false">
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
			    goods: {},
			    product: {
			      tags: ["热卖", "新鲜保障", "顺丰快达"],
			      specGroups: [{
			        name: "配送时间", // 补充规格组名称，与模板的spec-group-name对应
			        options: [{ label: "立即配送", value: "now" },
			                  { label: "9-12点", value: "morning" },
			                  { label: "13点-18点", value: "afternoon" },
			                  { label: "19点-21点", value: "evening" }],
			        selectedValue: "now"
			      }],
			      stock: 10,
			    },
			    currentImgIndex: 0,
			    quantity: 1
			  };
			},
			onLoad(options) {
			  // 接收分类页传递的商品数据（含intro），并容错处理
			  if (options.goods) {
			    this.goods = JSON.parse(decodeURIComponent(options.goods)) || {};
			  };
		},
		methods: {
			// 返回上一页
			navigateBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 选择商品规格
			selectSpec(groupIndex, value) {
				this.product.specGroups[groupIndex].selectedValue = value;
			},

			// 减少数量
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--;
				}
			},

			// 增加数量
			increaseQuantity() {
				if (this.quantity < this.product.stock) {
					this.quantity++;
				}
			},

			  // 加入购物车逻辑
			    // 修改 addToCart 方法
			    addToCart() {
			      let cartList = uni.getStorageSync('cartList') || [];
			      // 构建完整商品信息（包含规格和数量）
			      const goodsToAdd = {
			        ...this.goods,
			        count: this.quantity, // 使用当前选择的数量
			        specGroups: this.product.specGroups, // 规格组信息
			        specText: this.getSpecText() // 规格文本
			      };
			      
			      // 检查是否存在相同商品（考虑规格）
			      const existingIndex = cartList.findIndex(item => 
			        item.id === this.goods.id && // 建议用id判断更准确
			        JSON.stringify(item.specGroups) === JSON.stringify(this.product.specGroups)
			      );
			      
			      if (existingIndex > -1) {
			        // 已存在则累加数量
			        cartList[existingIndex].count += this.quantity;
			      } else {
			        // 不存在则添加新商品
			        cartList.push(goodsToAdd);
			      }
			      
			      uni.setStorageSync('cartList', cartList);
			      uni.showToast({
			        title: '加入购物车成功',
			        icon: 'success',
			      });
			    },

			// product-detail-page 的 goToCheckout 方法
			goToCheckout() {
			  const currentGoods = {
			    id: this.goods.id,
			    name: this.goods.name,
			    imageUrl: this.goods.image,
			    price: parseFloat(this.goods.price) || 0, // 确保价格为数字
			    quantity: this.quantity,
			    spec: this.getSpecText()
			  };
			  const cartData = encodeURIComponent(JSON.stringify([currentGoods]));
			  uni.navigateTo({
			    url: "/pages/goodsDetail/checkout?cartData=" + cartData
			  });
			},
			getSpecText() {
			  return this.product.specGroups.map(group => {
			    const option = group.options.find(item => item.value === group.selectedValue);
			    return `${group.name}: ${option ? option.label : '无'}`;
			  }).join(', ');
			},

			// 关闭弹窗
			closePopup() {
				this.$refs.cartPopup.close();
			},

			// 前往购物车
			goToCart() {
				this.$refs.cartPopup.close();
				uni.switchTab({
					url: "/pages/cart/cart"
				});
			},

			// 模拟从接口获取商品详情
			fetchProductDetail(productId) {
				// 实际项目中这里会有真实的接口请求
				setTimeout(() => {
					// 模拟获取数据后的处理
					console.log(`获取商品 ${productId} 的详情`);
				}, 500);
			}
		},
	};
</script>

<style scoped>
	.product-detail-page {
	  overflow-y: auto; 
	  min-height: 115vh; 
	}
	
	.goods-img {
	  width: 100%;
	  height: auto; 
	  display: block;
	}

	/* 商品信息样式 */
	.goods-info {
		padding: 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #eeeeee;
	}
	
	.goods-intro {
	  display: block; /* 独占一行 */
	  font-size: 14px;
	  color: #666666;
	  line-height: 1.6;
	  margin: 8px 0; /* 上下留白，区分价格和标签 */
	}


	.goods-name {
		font-size: 18px;
		font-weight: 500;
		color: #333333;
		margin-bottom: 8px;
		line-height: 1.4;
	}

	.price {
			font-size: 14px;
			color: #999999;
			margin-left: auto;
		}

	.product-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}

	.tag {
		font-size: 12px;
		color: #ff4d4f;
		background-color: #fff1f0;
		padding: 2px 8px;
		border-radius: 4px;
	}

	/* 规格选择样式 */
	.product-spec {
		padding: 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #eeeeee;
	}

	.spec-title {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
		margin-bottom: 12px;
	}

	.spec-group {
		margin-bottom: 16px;
	}

	.spec-group:last-child {
		margin-bottom: 0;
	}

	.spec-group-name {
		font-size: 14px;
		color: #666666;
		margin-bottom: 8px;
	}

	.spec-options {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
	}

	.spec-option {
		font-size: 14px;
		padding: 8px 16px;
		border: 1px solid #dddddd;
		border-radius: 4px;
		color: #333333;
		background-color: #ffffff;
	}

	.spec-option-selected {
		border-color: #007aff;
		color: #007aff;
		background-color: #f0f7ff;
	}

	/* 数量选择样式 */
	.product-quantity {
		padding: 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #eeeeee;
		display: flex;
		align-items: center;
	}

	.quantity-title {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
		width: 100px;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		margin-left: 16px;
	}

	.quantity-btn {
		width: 30px;
		height: 30px;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px solid #dddddd;
		background-color: #ffffff;
		font-size: 18px;
	}

	.quantity-btn.minus {
		border-right: none;
		border-radius: 4px 0 0 4px;
	}

	.quantity-btn.plus {
		border-left: none;
		border-radius: 0 4px 4px 0;
	}

	.quantity-btn.disabled {
		color: #cccccc;
		background-color: #f5f5f5;
	}

	.quantity-input {
		width: 40px;
		height: 30px;
		border-top: 1px solid #dddddd;
		border-bottom: 1px solid #dddddd;
		text-align: center;
		font-size: 18px;
	}

	.stock-info {
		font-size: 14px;
		color: #999999;
		margin-left: auto;
	}

	/* 底部操作栏样式 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		display: flex;
		background-color: #ffffff;
		border-top: 1px solid #eeeeee;
	}

	.cart-btn {
		flex: 1;
		background-color: #ff9800;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
	}

	.cart-btn uni-icons {
		margin-right: 5px;
	}

	.buy-btn {
		flex: 1;
		background-color: #ff4d4f;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
	}

	/* 弹窗样式 */
	.popup-content {
		background-color: #ffffff;
		border-radius: 10px;
		padding: 30px 20px;
		width: 80%;
		max-width: 300px;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.popup-text {
		font-size: 16px;
		color: #333333;
		margin: 20px 0;
	}

	.popup-buttons {
		display: flex;
		width: 100%;
		margin-top: 10px;
	}

	.popup-btn {
		flex: 1;
		height: 40px;
		line-height: 40px;
		text-align: center;
		border-radius: 5px;
		margin: 0 5px;
		font-size: 14px;
		background-color: #f5f5f5;
		color: #333333;
		border: none;
	}

	.popup-btn.go-cart {
		background-color: #007aff;
		color: #ffffff;
	}
</style>